package com.wlit.tianping;

import com.wlit.WlitBrowserApp;
import gnu.io.*;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.CompletableFuture;

public class TianpingService implements SerialPortEventListener{

    private static Logger logger = Logger.getLogger(TianpingService.class);

    private static TianpingService instance;

    public static TianpingService getInstance() {
        if (instance == null) {
            instance = new TianpingService();
        }
        return instance;
    }

    private TianpingService(){
    }

    private SerialPort serialPort;
    private InputStream inputStream;
    private OutputStream outputStream;
    private Map<String,String> theResultMap = new HashMap<>();
    private boolean blnOpen = false;
    private CompletableFuture<String> future;
    public void openComm(String portName){
        CommPortIdentifier commPortIdentifier = null;
        try {
            commPortIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        } catch (NoSuchPortException e) {
            logger.error("端口不存在",e);
            return;
        }
        CommPort commPort = null;
        try {
            commPort = commPortIdentifier.open(portName, 5000);
        } catch (PortInUseException e) {
            logger.error("端口被占用",e);
            return;
        }
        if (commPort == null){
            System.out.println("端口不存在");
            return;
        }

        if (commPort instanceof SerialPort) {
            try {
                serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
                serialPort.notifyOnDataAvailable(true);
                inputStream = serialPort.getInputStream();
                outputStream = serialPort.getOutputStream();
                serialPort.addEventListener(this);
                this.blnOpen = true;
            } catch (UnsupportedCommOperationException e) {
                logger.error("端口配置错误",e);
            } catch (TooManyListenersException e){
                logger.error("端口监听异常",e);
            }catch (IOException e){
                logger.error("IO异常",e);
            }
        }
    }

    public boolean sendData(String data){
        this.future = new CompletableFuture<>();
        if (outputStream != null){
            try {
                outputStream.write(data.getBytes(StandardCharsets.UTF_8));
                outputStream.flush();
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public void closeComm(){
        this.blnOpen = false;
        if (inputStream != null){
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (outputStream != null){
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (serialPort != null){
            serialPort.notifyOnDataAvailable(false);
            serialPort.removeEventListener();
            serialPort.close();
        }
    }


    @Override
    public void serialEvent(SerialPortEvent p0) {
        if (p0.getEventType() == SerialPortEvent.DATA_AVAILABLE){
            try {
                theResultMap.clear();
                Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name());
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    logger.info(">>>"+line);
                    if (line != null && line.length() > 0) {
                        String[] arr = line.split(":");
                        String key = arr[0];
                        String value = arr[1].trim();//可能包含很多的空格
                        theResultMap.put(key,value);
                    }
                }

                if (theResultMap.containsKey("WT")){
                    String value = theResultMap.get("WT");
                    String dataValue = "";
                    //根据不同的单位进行处理
                    if (value.endsWith("kg")) {
                        dataValue = value.substring(0, value.length() - 2);
                    }else if (value.endsWith("mg")){
                        dataValue = value.substring(0, value.length() - 2);
                    }else if (value.endsWith("g")){
                        dataValue = value.substring(0, value.length() - 1);
                    }
                    logger.info("称重结果:"+value+"@"+dataValue);
                    future.complete(dataValue);
                    for (IDataListener dataListener : WlitBrowserApp.dataListeners) {
                        dataListener.onReceiver(dataValue);
                    }
                }

            } catch (Exception e) {
                future.completeExceptionally(e);
                e.printStackTrace();
            }
        }
    }

    public CompletableFuture<String> getData(){
        return future;
    }

    public boolean isOpen(){
        return blnOpen;
    }
}
